//
//  UITextFieldController.swift
//  HHSwift
//
//  Created by qk-huahong on 2019/5/20.
//  Copyright © 2019 huahong. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import ReactiveCocoa
import ReactiveSwift

class UITextFieldController: BaseViewController,UITextFieldDelegate {
    let label = UILabel()
    let textField = UITextField()
    let disposeBag = DisposeBag()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "UITextField & UILabel"
        
        view.addSubview(label)
        view.addSubview(textField)
 
        
//MARK: - textField
        textField.delegate = self
        textField.layer.borderColor = UIColor.lightGray.cgColor
        textField.layer.borderWidth = 1
        textField.placeholder = "请输入..."
//        textField.borderStyle = .roundedRect
        textField.textColor = .black
        textField.font = UIFont.systemFont(ofSize: 18)
        textField.textAlignment = .left
        textField.clearsOnBeginEditing = true//每次开始输入，清空oldvalue
        textField.minimumFontSize = 10
        textField.adjustsFontSizeToFitWidth = true
//        textField.background = UIImage(named: "04")//受borderStyle影响
//        textField.disabledBackground = UIImage(named: "03")
        textField.clearButtonMode = .whileEditing
        
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
        leftView.backgroundColor = .red
//        textField.leftView = leftView
//        textField.leftViewMode = .always
        let borderRect = textField.borderRect(forBounds: CGRect(x: 0, y: 0, width: 200, height: 40))
        print(borderRect)
        textField.isSecureTextEntry = false
        textField.inputView = self.datePicker;//替代系统键盘
        textField.inputAccessoryView = toolBar;//出现在键盘上面
        
   
        
//MARK: - label
        label.backgroundColor = .cyan
        label.numberOfLines = 0
       


        
//MARK: - layout
        ///设置优先级
//        leftLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
        label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(30)
            make.top.equalToSuperview().offset(100)
            make.right.equalToSuperview().offset(-30)
            make.height.greaterThanOrEqualTo(30)
        }
        
        
        textField.snp.makeConstraints { (make) in
            make.left.equalTo(label.snp.left)
            make.top.equalTo(label.snp.bottom).offset(30)
            make.right.equalTo(label.snp.right)
            make.height.equalTo(40)
        }
        
//MARK: - RxSwift
        //当文本框内容改变时，将内容输出到控制台上
        textField.rx.text.orEmpty.asObservable()
            .subscribe(onNext: {text in
                print("您输入的是：\(text)")
//                self?.label.text = text;
            })
            .disposed(by:disposeBag)
        
        textField.rx.text.orEmpty.changed
            .subscribe(onNext: {text in
                print("changed：\(text)")
//                self?.label.text = text;
            })
            .disposed(by:disposeBag)
        
        textField.rx.text
        .bind(to: label.rx.text)
        .disposed(by: disposeBag)
    
        textField.rx.controlEvent(.editingDidEndOnExit)
            .subscribe(onNext: {[weak self] (_) in
                self?.textField.resignFirstResponder()
        }).disposed(by: disposeBag)
       
        //Optional
//        textField.rx.text.subscribe(onNext: {
//            print( $0 )
//        }).disposed(by: disposeBag)
        
        
        
        
        
        
    }
    
    
    // MARK: - UITextFieldDelegate

    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }

    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
//        let fullText = textField.text.stringb
        
        
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        textField.selectAllText()
        
//        textField.setSelectedRange(range: NSMakeRange(1, 5))
        
        textField.setMarkedText("mark", selectedRange: NSMakeRange(1, 5))
        
//        textField.selectAll(nil)
    }
    
    lazy var datePicker: UIDatePicker = {

       let datePicker = UIDatePicker()
       datePicker.backgroundColor = .white
       datePicker.frame = CGRect(x: 0, y: UIScreen.main.bounds.size.height - 216, width: UIScreen.main.bounds.size.width, height: 216)
       datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.datePickerMode = .date
       datePicker.date = Date()
       
          
          return datePicker
      }()
    
    lazy var toolBar: UIToolbar = {
        let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: UIScreen.main.bounds.size.height - self.datePicker.bounds.size.height - 40, width: UIScreen.main.bounds.size.width, height: 40))
        toolBar.backgroundColor = UIColor.white
        let leftItem = UIBarButtonItem.init(title: "  取消", style: .plain, target: self, action: #selector(cancelBtnClicked))
        let centerItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
        let rightItem = UIBarButtonItem(title: "确定  ", style: .plain, target: self, action: #selector(sureBtnClicked))
        toolBar.items = [leftItem,centerItem,rightItem]
        return toolBar
    }()
    
    //MARK: - Action:
    @objc func cancelBtnClicked() {
        
        textField.resignFirstResponder()
    }
    
    @objc func sureBtnClicked() {

       
        
     let formatter = DateFormatter()
         formatter.dateFormat = "yyyy-MM-dd"
         formatter.locale = Locale(identifier: "zh_CN")
     let dateString =  formatter.string(from: datePicker.date)
        
         textField.text = dateString
        textField.resignFirstResponder()

       
    }
    
}
